#include "myword.h"
#include <QtWidgets>
#include <QPrintDialog>
#include <QPrintPreviewDialog>
#include <QColorDialog>
#include <QTextCharFormat>

const QString rsrcPath = ":/images";
MyWord::MyWord(QWidget *parent)
    : QMainWindow(parent)
{
    mdiArea = new QMdiArea;
    mdiArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);   //设置滚动条，子窗口较多，主窗口显示不下时
    mdiArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    setCentralWidget(mdiArea);  //设置中心控件
    void (QMdiArea::*subWindowActivated)(QMdiSubWindow*) = &QMdiArea::subWindowActivated;
    connect(mdiArea,subWindowActivated,this,&MyWord::updateMenus);

    createActions();
    createMenus();
    createToolBars();
    createStatusBar();
    updateMenus();

    move(200,150);
    resize(800,500);

    //创建信号映射器
    windowMapper = new QSignalMapper(this);
    //映射器重新发射信号,根据信号设置活动窗口
//    void (QSignalMapper::*mapper)(QObject*) = &QSignalMapper::mappedObject;
//    void (QMdiArea::*setActiveSubWindow)(QMdiSubWindow*) = &QMdiArea::setActiveSubWindow;
//    connect(windowMapper,mapper,this,setActiveSubWindow);

    setWindowTitle("Myself Word");
    setUnifiedTitleAndToolBarOnMac(true);
}

void MyWord::createActions()
{
    //"文件"主菜单动作集
    newAct = new QAction(QIcon(rsrcPath+"/new.png"),"新建(&N)",this);
    newAct->setShortcut(QKeySequence::New); //设置快捷键
    newAct->setToolTip("新建");
    newAct->setStatusTip("创建一个新文档"); //状态栏说明
    connect(newAct,&QAction::triggered,this,&MyWord::fileNew);

    openAct = new QAction(QIcon(rsrcPath+"/open.png"),"打开(&O)...",this);
    openAct->setShortcut(QKeySequence::Open);
    openAct->setToolTip("打开");
    openAct->setStatusTip("打开已存在的文档");
    connect(openAct,&QAction::triggered,this,&MyWord::fileOpen);

    saveAct = new QAction(QIcon(rsrcPath+"/save.png"),"保存(&S)",this);
    saveAct->setShortcut(QKeySequence::Save);
    saveAct->setToolTip("保存");
    saveAct->setStatusTip("将当前文档存盘");
    connect(saveAct,&QAction::triggered,this,&MyWord::fileSave);

    saveAsAct = new QAction("另存为(&A)...",this);
    saveAsAct->setShortcut(QKeySequence::SaveAs);
    saveAsAct->setStatusTip("以一个新名字保存文档");
    connect(saveAsAct,&QAction::triggered,this,&MyWord::fileSaveAs);

    printAct = new QAction(QIcon(rsrcPath+"/printer.png"),"打印(&P)...",this);
    printAct->setShortcut(QKeySequence::Print);
    printAct->setToolTip("打印");
    printAct->setStatusTip("打印文档");
    connect(printAct,&QAction::triggered,this,&MyWord::filePrint);

    printPreviewAct = new QAction("打印预览...",this);
    printPreviewAct->setStatusTip("预览打印效果");
    connect(printPreviewAct,&QAction::triggered,this,&MyWord::filePrintPreview);

    exitAct = new QAction("退出(&X)...",this);
    exitAct->setShortcut(QKeySequence::Quit);
    exitAct->setStatusTip("退出应用程序");
    connect(exitAct,&QAction::triggered,qApp,&QApplication::closeAllWindows);

    //"编辑"主菜单动作集
    undoAct = new QAction(QIcon(rsrcPath+"/undo.png"),"撤销(&U)",this);
    undoAct->setShortcut(QKeySequence::Undo);
    undoAct->setToolTip("撤销");
    undoAct->setStatusTip("撤销当前操作");
    connect(undoAct,&QAction::triggered,this,&MyWord::undo);

    redoAct = new QAction(QIcon(rsrcPath+"/redo.png"),"重做(&R)",this);
    redoAct->setShortcut(QKeySequence::Redo);
    redoAct->setToolTip("重做");
    redoAct->setStatusTip("恢复之前操作");
    connect(redoAct,&QAction::triggered,this,&MyWord::redo);

    cutAct = new QAction(QIcon(rsrcPath+"/cut.png"),"剪切(&T)",this);
    cutAct->setShortcut(QKeySequence::Cut);
    cutAct->setToolTip("剪切");
    cutAct->setStatusTip("从文档中裁剪所选内容，并将其放入剪贴板");
    connect(cutAct,&QAction::triggered,this,&MyWord::cut);

    copyAct = new QAction(QIcon(rsrcPath+"/copy.png"),"复制(&C)",this);
    copyAct->setShortcut(QKeySequence::Copy);
    copyAct->setToolTip("复制");
    copyAct->setStatusTip("复制所选内容，并将其放入剪贴板");
    connect(copyAct,&QAction::triggered,this,&MyWord::copy);

    pasteAct = new QAction(QIcon(rsrcPath+"/paste.png"),"粘贴(&P)",this);
    pasteAct->setShortcut(QKeySequence::Paste);
    pasteAct->setToolTip("粘贴");
    pasteAct->setStatusTip("将剪贴板的内容粘贴到文档");
    connect(pasteAct,&QAction::triggered,this,&MyWord::paste);

    //"格式"主菜单动作集
    boldAct = new QAction(QIcon(rsrcPath+"/bold.png"),"加粗(&B)",this);
    boldAct->setCheckable(true);
    boldAct->setShortcut(Qt::CTRL | Qt::Key_B);
    boldAct->setToolTip("加粗");
    boldAct->setStatusTip("将所选文字加粗");
    QFont bold;
    bold.setBold(true);
    boldAct->setFont(bold);
    connect(boldAct,&QAction::triggered,this,&MyWord::textBold);

    italicAct = new QAction(QIcon(rsrcPath+"/italic.png"),"倾斜(&I)",this);
    italicAct->setCheckable(true);
    italicAct->setShortcut(Qt::CTRL | Qt::Key_I);
    italicAct->setToolTip("倾斜");
    italicAct->setStatusTip("将所选文字用倾斜显示");
    QFont italic;
    italic.setItalic(true);
    italicAct->setFont(italic);
    connect(italicAct,&QAction::triggered,this,&MyWord::textItalic);

    underlineAct = new QAction(QIcon(rsrcPath+"/under.png"),"下划线(&U)",this);
    underlineAct->setCheckable(true);
    underlineAct->setShortcut(Qt::CTRL | Qt::Key_U);
    underlineAct->setToolTip("下划线");
    underlineAct->setStatusTip("为所选文字用加下划线");
    QFont underline;
    underline.setUnderline(true);
    underlineAct->setFont(italic);
    connect(underlineAct,&QAction::triggered,this,&MyWord::textUnderline);

    QActionGroup *grp = new QActionGroup(this);
    void (QActionGroup::*triggered)(QAction*) = &QActionGroup::triggered;
    void (MyWord::*textAlign)(QAction*) = &MyWord::textAlign;
    connect(grp,triggered,this,textAlign);

    if(QApplication::isLeftToRight())
    {
        leftAlignAct = new QAction(QIcon(rsrcPath+"/left.png"),"左对齐(&L)",grp);
        centerAct = new QAction(QIcon(rsrcPath+"/center.png"),"居中(&E)",grp);
        rightAlignAct = new QAction(QIcon(rsrcPath+"/right.png"),"右对齐(&R)",grp);
    }
    else
    {
        rightAlignAct = new QAction(QIcon(rsrcPath+"/right.png"),"右对齐(&R)",grp);
        centerAct = new QAction(QIcon(rsrcPath+"/center.png"),"居中(&E)",grp);
        leftAlignAct = new QAction(QIcon(rsrcPath+"/left.png"),"左对齐(&L)",grp);
    }
    justifyAct = new QAction(QIcon(rsrcPath+"/justify.png"),"两端对齐(&J)",grp);

    leftAlignAct->setCheckable(true);
    leftAlignAct->setShortcut(Qt::CTRL | Qt::Key_L);
    leftAlignAct->setToolTip("左对齐");
    leftAlignAct->setStatusTip("将文字左对齐");

    centerAct->setCheckable(true);
    centerAct->setShortcut(Qt::CTRL | Qt::Key_E);
    centerAct->setToolTip("居中");
    centerAct->setStatusTip("将文字居中对齐");

    rightAlignAct->setCheckable(true);
    rightAlignAct->setShortcut(Qt::CTRL | Qt::Key_R);
    rightAlignAct->setToolTip("右对齐");
    rightAlignAct->setStatusTip("将文字右对齐");

    justifyAct->setCheckable(true);
    justifyAct->setShortcut(Qt::CTRL | Qt::Key_J);
    justifyAct->setToolTip("两端对齐");
    justifyAct->setStatusTip("将文字左右两端同时对齐,并根据需要增加字间距");

    QPixmap pix(16,16);
    pix.fill(Qt::red);
    colorAct = new QAction(pix,"颜色(&C)...",this);
    colorAct->setToolTip("颜色");
    colorAct->setStatusTip("设置文字颜色");
    connect(colorAct,&QAction::triggered,this,&MyWord::textColor);

    //"窗口"主菜单动作集
    closeAct = new QAction("关闭(&O)",this);
    closeAct->setStatusTip("关闭活动文档子窗口");
    connect(closeAct,&QAction::triggered,mdiArea,&QMdiArea::closeActiveSubWindow);

    closeAllAct = new QAction("关闭所有(&O)",this);
    closeAllAct->setStatusTip("关闭所有子窗口");
    connect(closeAllAct,&QAction::triggered,mdiArea,&QMdiArea::closeAllSubWindows);

    tileAct = new QAction("平铺(&T)",this);
    tileAct->setStatusTip("平铺子窗口");
    connect(tileAct,&QAction::triggered,mdiArea,&QMdiArea::tileSubWindows);

    cascadeAct = new QAction("层叠(&C)",this);
    cascadeAct->setStatusTip("层叠子窗口");
    connect(cascadeAct,&QAction::triggered,mdiArea,&QMdiArea::cascadeSubWindows);

    nextAct = new QAction("下一个(&X)",this);
    nextAct->setShortcut(QKeySequence::NextChild);
    nextAct->setStatusTip("移动焦点到下一个子窗口");
    connect(nextAct,&QAction::triggered,mdiArea,&QMdiArea::activateNextSubWindow);

    previousAct = new QAction("前一个(&V)",this);
    previousAct->setShortcut(QKeySequence::PreviousChild);
    previousAct->setStatusTip("移动焦点到前一个子窗口");
    connect(nextAct,&QAction::triggered,mdiArea,&QMdiArea::activatePreviousSubWindow);

    separatorAct = new QAction(this);
    separatorAct->setSeparator(true);

    //"帮助"主菜单动作集
    aboutAct = new QAction("关于(&A)",this);
    aboutAct->setStatusTip("关于Myself Word");
    connect(aboutAct,&QAction::triggered,this,&MyWord::about);

    aboutQtAct = new QAction("关于Qt(&Q)",this);
    aboutQtAct->setStatusTip("关于Qt库");
    connect(aboutQtAct,&QAction::triggered,qApp,&QApplication::aboutQt);
}

void MyWord::createMenus()
{
    // //"文件"主菜单
    // fileMenu = menuBar()->addMenu("文件(&F)");
    // fileMenu->addAction(newAct);
    // fileMenu->addAction(openAct);
    // fileMenu->addSeparator();//分割线
    // fileMenu->addAction(saveAct);
    // fileMenu->addAction(saveAsAct);
    // fileMenu->addSeparator();//分割线
    // fileMenu->addAction(printAct);
    // fileMenu->addAction(printPreviewAct);
    // fileMenu->addSeparator();//分割线
    // fileMenu->addAction(exitAct);

    // //"编辑"主菜单
    // editMenu = menuBar()->addMenu("编辑(&E)");
    // editMenu->addAction(undoAct);
    // editMenu->addAction(redoAct);
    // editMenu->addSeparator();//分割线
    // editMenu->addAction(cutAct);
    // editMenu->addAction(copyAct);
    // editMenu->addAction(pasteAct);

    // //"格式"主菜单
    // formatMenu = menuBar()->addMenu("格式(&O)");
    // fontMenu = menuBar()->addMenu("字体(&D)");
    // fontMenu->addAction(boldAct);
    // fontMenu->addAction(italicAct);
    // fontMenu->addAction(underlineAct);

    // alignMenu = menuBar()->addMenu("段落");
    // alignMenu->addAction(leftAlignAct);
    // alignMenu->addAction(centerAct);
    // alignMenu->addAction(rightAlignAct);
    // alignMenu->addAction(justifyAct);

    // formatMenu->addAction(colorAct);

    // //"窗口"主菜单
    // windowMenu = menuBar()->addMenu("窗口(&W)");
    // updateWindowMenu();
    // connect(windowMenu,&QMenu::aboutToShow,this,&MyWord::updateWindowMenu);
    // menuBar()->addSeparator();

    // //"帮助"主菜单
    // helpMenu = menuBar()->addMenu("帮助(&H)");
    // helpMenu->addAction(aboutAct);
    // helpMenu->addSeparator();
    // helpMenu->addAction(aboutQtAct);

    // Helper function for adding actions and separators
    auto addMenuActions = [](QMenu *menu, const QList<QAction *> &actions) {
        for (QAction *action : actions) {
            menu->addAction(action);
        }
    };

    // "文件"主菜单
    fileMenu = menuBar()->addMenu("文件(&F)");
    addMenuActions(fileMenu, { newAct, openAct });
    fileMenu->addSeparator(); // 分割线
    addMenuActions(fileMenu, { saveAct, saveAsAct });
    fileMenu->addSeparator(); // 分割线
    addMenuActions(fileMenu, { printAct, printPreviewAct });
    fileMenu->addSeparator(); // 分割线
    fileMenu->addAction(exitAct);

    // "编辑"主菜单
    editMenu = menuBar()->addMenu("编辑(&E)");
    addMenuActions(editMenu, { undoAct, redoAct });
    editMenu->addSeparator(); // 分割线
    addMenuActions(editMenu, { cutAct, copyAct, pasteAct });

    // "格式"主菜单
    formatMenu = menuBar()->addMenu("格式(&O)");
    fontMenu = formatMenu->addMenu("字体(&D)"); // Nested menu for font actions
    addMenuActions(fontMenu, { boldAct, italicAct, underlineAct });

    alignMenu = formatMenu->addMenu("段落"); // Nested menu for paragraph alignment
    addMenuActions(alignMenu, { leftAlignAct, centerAct, rightAlignAct, justifyAct });

    formatMenu->addAction(colorAct);

    // "窗口"主菜单
    windowMenu = menuBar()->addMenu("窗口(&W)");
    updateWindowMenu();
    connect(windowMenu, &QMenu::aboutToShow, this, &MyWord::updateWindowMenu);
    menuBar()->addSeparator();

    // "帮助"主菜单
    helpMenu = menuBar()->addMenu("帮助(&H)");
    addMenuActions(helpMenu, { aboutAct });
    helpMenu->addSeparator();
    helpMenu->addAction(aboutQtAct);
}

void MyWord::createToolBars()
{
    //"文件"工具条
    fileToolBar = addToolBar("文件");
    fileToolBar->addAction(newAct);
    fileToolBar->addAction(openAct);
    fileToolBar->addAction(saveAct);
    fileToolBar->addSeparator();
    fileToolBar->addAction(printAct);

    //"编辑"工具条
    editToolBar = addToolBar("编辑");
    editToolBar->addAction(undoAct);
    editToolBar->addAction(redoAct);
    editToolBar->addSeparator();
    editToolBar->addAction(cutAct);
    editToolBar->addAction(copyAct);
    editToolBar->addAction(pasteAct);

    //"格式"工具条
    formatToolBar = addToolBar("格式");
    formatToolBar->addAction(boldAct);
    formatToolBar->addAction(italicAct);
    formatToolBar->addAction(underlineAct);
    formatToolBar->addSeparator();
    formatToolBar->addAction(leftAlignAct);
    formatToolBar->addAction(centerAct);
    formatToolBar->addAction(rightAlignAct);
    formatToolBar->addAction(justifyAct);
    formatToolBar->addSeparator();
    formatToolBar->addAction(colorAct);

    //组合选择框
    addToolBarBreak(Qt::TopToolBarArea);
    comboToolBar = addToolBar("组合选择");
    comboStyle = new QComboBox();
    comboToolBar->addWidget(comboStyle);
    comboStyle->addItem("标准");
    comboStyle->addItem("项目符号(●)");
    comboStyle->addItem("项目符号(○)");
    comboStyle->addItem("项目符号(■)");
    comboStyle->addItem("编号(⒈⒉⒊)");
    comboStyle->addItem("编号(a.b.c.)");
    comboStyle->addItem("编号(A.B.C.)");
    comboStyle->addItem("编号(ⅰ.ⅱ.ⅲ.)");
    comboStyle->addItem("编号(Ⅰ.Ⅱ.Ⅲ.)");
    comboStyle->setStatusTip("段落加标号或编号");
    void (QComboBox::*activat)(int) = &QComboBox::activated;
    void (MyWord::*textStyle)(int) = &MyWord::textStyle;
    connect(comboStyle,activat,this,textStyle);

    comboFont = new QFontComboBox();
    comboToolBar->addWidget(comboFont);
    comboFont->setStatusTip("更改字体");
    void (QFontComboBox::*textActivated)(const QString&) = &QFontComboBox::textActivated;
    void (MyWord::*textFamily)(const QString&) = &MyWord::textFamily;
    connect(comboFont,textActivated,this,textFamily);

    comboSize = new QComboBox();
    comboToolBar->addWidget(comboSize);
    comboSize->setEditable(true);
    comboSize->setStatusTip("更改字号");

    QFontDatabase db;
    foreach (int size, db.standardSizes()) {
        comboSize->addItem(QString::number(size));
    }
    void (QComboBox::*activated)(int) = &QComboBox::activated;
    void (MyWord::*textSize)(int) = &MyWord::textSize;
    connect(comboSize,activated,this,textSize);
    //comboSize->setCurrentIndex(comboSize->findText(QString::number(QApplication::font().pointSize())));
}

void MyWord::textAlign(QAction *a)
{
    if(activeMyChild())
    {
        if(a == leftAlignAct)
            activeMyChild()->setAlign(1);
        else if(a == centerAct)
            activeMyChild()->setAlign(2);
        else if(a == rightAlignAct)
            activeMyChild()->setAlign(3);
        else if(a == justifyAct)
            activeMyChild()->setAlign(4);
    }
}

void MyWord::about()
{
    QMessageBox::about(this,"关于","这是基于Qt实现的文字处理软件,具备类似微软office Word功能");
}

MyChild *MyWord::createMyChild()
{
    MyChild *child = new MyChild;   //创建MyChild部件
    mdiArea->addSubWindow(child);   //向多文档添加子窗口,child为中心部件
    void (MyChild::*cutAvailable)(bool) = &MyChild::copyAvailable;
    void (QAction::*cutEnabled)(bool) = &QAction::setEnabled;
    connect(child,cutAvailable,cutAct,cutEnabled);

    void (MyChild::*copyAvailable)(bool) = &MyChild::copyAvailable;
    void (QAction::*copyEnabled)(bool) = &QAction::setEnabled;
    connect(child,copyAvailable,copyAct,copyEnabled);

    return child;
}

void MyWord::fileNew()
{
    MyChild *child = createMyChild();
    child->newFile();
    child->show();
    enabledText();
}

void MyWord::fileOpen()
{
    QString fileName = QFileDialog::getOpenFileName(this,"打开",QString(),"HTML文档(*.htm *.html);;所有文件(*.*)");
    if(!fileName.isEmpty())
    {
        QMdiSubWindow *existing = findMyChild(fileName);
        if(existing)
        {
            mdiArea->setActiveSubWindow(existing);
            return;
        }
        MyChild *child = createMyChild();
        if(child->loadFile(fileName))
        {
            statusBar()->showMessage("文件已载入",2000);
            child->show();
        }
        else
        {
            child->close();
        }
    }
    enabledText();
}

void MyWord::fileSave()
{
    if(activeMyChild() && activeMyChild()->save())
        statusBar()->showMessage("保存成功",2000);
}

void MyWord::fileSaveAs()
{
    if(activeMyChild() && activeMyChild()->saveAs())
        statusBar()->showMessage("保存成功",2000);
}

void MyWord::undo()
{
    if(activeMyChild())
        activeMyChild()->undo();
}

void MyWord::redo()
{
    if(activeMyChild())
        activeMyChild()->redo();
}

void MyWord::cut()
{
    if(activeMyChild())
        activeMyChild()->cut();
}

void MyWord::copy()
{
    if(activeMyChild())
        activeMyChild()->copy();
}

void MyWord::paste()
{
    if(activeMyChild())
        activeMyChild()->paste();
}

void MyWord::textBold()
{
    QTextCharFormat fmt;
    fmt.setFontWeight(boldAct->isChecked() ? QFont::Bold : QFont::Normal);
    if(activeMyChild())
        activeMyChild()->mergeFormatOnWordOrSelection(fmt);
}

void MyWord::textItalic()
{
    QTextCharFormat fmt;
    fmt.setFontItalic(italicAct->isChecked());
    if(activeMyChild())
        activeMyChild()->mergeFormatOnWordOrSelection(fmt);
}

void MyWord::textUnderline()
{
    QTextCharFormat fmt;
    fmt.setFontUnderline(underlineAct->isChecked());
    if(activeMyChild())
        activeMyChild()->mergeFormatOnWordOrSelection(fmt);
}

void MyWord::textFamily(const QString &f)
{
    QTextCharFormat fmt;
    fmt.setFont(QFont(f));
    if(activeMyChild())
        activeMyChild()->mergeFormatOnWordOrSelection(fmt);
}

void MyWord::textSize(int )
{
    int p = comboSize->currentText().toInt();
    qreal pointSize = p;
    if(p > 0)
    {
        QTextCharFormat fmt;
        fmt.setFontPointSize(pointSize);
        if(activeMyChild())
            activeMyChild()->mergeFormatOnWordOrSelection(fmt);
    }
}

void MyWord::textColor()
{
    if(activeMyChild())
    {
        QColor color = QColorDialog::getColor(activeMyChild()->textColor(),this);
        if(!color.isValid())
            return;
        QTextCharFormat fmt;
        fmt.setForeground(color);
        activeMyChild()->mergeFormatOnWordOrSelection(fmt);
        //colorSelected(color);
    }
}

void MyWord::textStyle(int styleIndex)
{
    if(activeMyChild())
    {
        activeMyChild()->setStyle(styleIndex);
    }
}

void MyWord::filePrint()
{
    QPrinter printer(QPrinter::HighResolution);
    QPrintDialog *dlg = new QPrintDialog(&printer,this);
    if(activeMyChild()->textCursor().hasSelection())
        dlg->setOption(QAbstractPrintDialog::PrintSelection);
    dlg->setWindowTitle("打印文档");
    if(dlg->exec() == QDialog::Accepted)
        activeMyChild()->print(&printer);
    delete dlg;
}

void MyWord::filePrintPreview()
{
    QPrinter printer(QPrinter::HighResolution);
    QPrintPreviewDialog preview(&printer,this);
    void (QPrintPreviewDialog::*paintRequested)(QPrinter*) = &QPrintPreviewDialog::paintRequested;
    void (MyWord::*printPreview)(QPrinter*) = &MyWord::printPreview;
    connect(&preview,paintRequested,this,printPreview);
    preview.exec();
}

void MyWord::printPreview(QPrinter *printer)
{
    activeMyChild()->print(printer);
}

QMdiSubWindow *MyWord::findMyChild(const QString &fileName)
{
    QString canonicalFilePath = QFileInfo(fileName).canonicalFilePath();

    foreach (QMdiSubWindow *window, mdiArea->subWindowList()) {
        MyChild *myChild = qobject_cast<MyChild *>(window->widget());
        if(myChild->currentFile() == canonicalFilePath)
            return window;
    }
    return 0;
}

void MyWord::enabledText()
{
    boldAct->setEnabled(true);
    italicAct->setEnabled(true);
    underlineAct->setEnabled(true);
    leftAlignAct->setEnabled(true);
    centerAct->setEnabled(true);
    rightAlignAct->setEnabled(true);
    justifyAct->setEnabled(true);
    colorAct->setEnabled(true);
}

void MyWord::updateMenus()
{
    //至少有一个子文档打开时的情况
    bool hasMyChild = (activeMyChild()!=0);

    saveAct->setEnabled(hasMyChild);
    saveAsAct->setEnabled(hasMyChild);
    printAct->setEnabled(hasMyChild);
    printPreviewAct->setEnabled(hasMyChild);

    pasteAct->setEnabled(hasMyChild);

    closeAct->setEnabled(hasMyChild);
    closeAllAct->setEnabled(hasMyChild);
    tileAct->setEnabled(hasMyChild);
    cascadeAct->setEnabled(hasMyChild);
    nextAct->setEnabled(hasMyChild);
    previousAct->setEnabled(hasMyChild);

    //设置分割条是否显示
    separatorAct->setVisible(hasMyChild);
    //文档打开并且其中有内容被选中的情况
    bool hasSelection = (activeMyChild() && activeMyChild()->textCursor().hasSelection());

    cutAct->setEnabled(hasSelection);
    copyAct->setEnabled(hasSelection);

    boldAct->setEnabled(hasSelection);
    italicAct->setEnabled(hasSelection);
    underlineAct->setEnabled(hasSelection);
    leftAlignAct->setEnabled(hasSelection);
    centerAct->setEnabled(hasSelection);
    rightAlignAct->setEnabled(hasSelection);
    justifyAct->setEnabled(hasSelection);
    colorAct->setEnabled(hasSelection);
}

MyChild *MyWord::activeMyChild()
{
    //如果有活动窗口,则将其内的中心部件转换为MyChild类型,没有则直接返回0
    if(QMdiSubWindow *activeSubWindow = mdiArea->activeSubWindow())
        return qobject_cast<MyChild *>(activeSubWindow->widget());
    return 0;
}

void MyWord::updateWindowMenu()
{
    //首先清空菜单,然后再添加各个菜单动作
    windowMenu->clear();
    windowMenu->addAction(closeAct);
    windowMenu->addAction(closeAllAct);
    windowMenu->addSeparator();
    windowMenu->addAction(tileAct);
    windowMenu->addAction(cascadeAct);
    windowMenu->addSeparator();
    windowMenu->addAction(nextAct);
    windowMenu->addAction(previousAct);
    windowMenu->addAction(separatorAct);

    //如果有活动窗口,则显示分割条
    QList<QMdiSubWindow *> windows = mdiArea->subWindowList();
    separatorAct->setVisible(!windows.isEmpty());
    //遍历各个子窗口,显示当前已打开的文档子窗口项
    for (int i = 0; i < windows.size(); ++i)
    {
        MyChild *child = qobject_cast<MyChild *>(windows.at(i)->widget());
        QString text;
        if(i < 9)
        {
            text = QString("&%1 %2").arg(i + 1).arg(child->userFriendlyCurrentFile());
        }
        else
        {
            text = QString("%1 %2").arg(i + 1).arg(child->userFriendlyCurrentFile());
        }
        //添加动作到菜单,设置动作可以选择
        QAction *action = windowMenu->addAction(text);
        action->setCheckable(true);
        //设置当前活动窗口动作为选中状态
        action->setChecked(child==activeMyChild());
        //关联动作的触发动作到信号映射器的map槽,这个槽会发射mapped信号
        connect(action,SIGNAL(triggered()),windowMapper,SLOT(map()));
    }
    enabledText();  //使得字体设置菜单可用
}

void MyWord::createStatusBar()
{
    statusBar()->showMessage("就绪");
}

void MyWord::closeEvent(QCloseEvent *event)
{
    mdiArea->closeAllSubWindows();
    if(mdiArea->currentSubWindow())
    {
        event->ignore();
    }
    else
    {
        event->accept();
    }
}

MyWord::~MyWord()
{
}

